package com.atguigu.dwm.lineage.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.dwm.common.bean.Result;
import com.atguigu.dwm.lineage.bean.LineageInfo;
import com.atguigu.dwm.lineage.service.LineageInfoService;
import com.atguigu.dwm.model.bean.DmTable;
import com.atguigu.dwm.model.service.DmTableService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 血缘关系表 前端控制器
 * </p>
 *
 * @author zhangchen
 * @since 2024-07-08
 */
@RestController
@RequestMapping("/lineage")
public class LineageInfoController {

        @Autowired
        DmTableService dmTableService;

        @Autowired
        LineageInfoService lineageInfoService;

        @GetMapping("/root/{tableId}")
        public Result getRoot(@PathVariable("tableId") Long tableId){
            DmTable rootTable = dmTableService.getById(tableId);
            LineageInfo lineageInfo = lineageInfoService.getOne(new QueryWrapper<LineageInfo>()
                    .eq("schema_name", rootTable.getSchemaName())
                    .eq("table_name", rootTable.getTableName())
            );

            //取所有表的集合转成map 用户翻译中文表名
            List<DmTable> dmTableList = dmTableService.list(new QueryWrapper<DmTable>().eq("is_deleted", "0"));
            Map<String, String> tableNameMap = dmTableList.stream().collect(Collectors.toMap(dmTable -> dmTable.getSchemaName() + "." + dmTable.getTableName(), dmTable ->  dmTable.getTableNameChn()==null?"":dmTable.getTableNameChn()));

            if(lineageInfo==null){
                return Result.error("没有找到该表");
            }

            List<JSONObject> childList =  new ArrayList<>();
            //处理上游子节点
            String sourceTables = lineageInfo.getSourceTables();
            if(sourceTables!=null) {
                String[] sourceTableFullNameArr = sourceTables.split(",");
                for (String sourceTableFullName : sourceTableFullNameArr) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", sourceTableFullName);
                    jsonObject.put("relation", "source");
                    String tableNameChn = tableNameMap.get(sourceTableFullName);
                    if (tableNameChn != null) {
                        jsonObject.put("comment", tableNameChn);
                    }
                    childList.add(jsonObject);
                }
            }

            //处理下游子节点
            String sinkTables = lineageInfo.getSinkTables();
            if(sinkTables!=null) {
                String[] sinkTableFullNameArr = sinkTables.split(",");
                for (String sinkTableFullName  : sinkTableFullNameArr) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", sinkTableFullName);
                    jsonObject.put("relation", "sink");
                    String tableNameChn = tableNameMap.get(sinkTableFullName);
                    if (tableNameChn != null) {
                        jsonObject.put("comment", tableNameChn);
                    }
                    childList.add(jsonObject);
                }
            }

            //组装根节点
            JSONObject rootJsonObj = new JSONObject();
            rootJsonObj.put("isRoot", true);
            rootJsonObj.put("children",childList);
            rootJsonObj.put("id",rootTable.getSchemaName()+"."+rootTable.getTableName());
            rootJsonObj.put("comment",rootTable.getTableNameChn());

            return Result.ok(rootJsonObj);

        }

        @GetMapping("/child/{tableName}")
        public  Result getChild(@PathVariable("tableName") String tableFullName, @RequestParam("relation")String relation){

            //取所有表的集合转成map 用户翻译中文表名
            List<DmTable> dmTableList = dmTableService.list(new QueryWrapper<DmTable>().eq("is_deleted", "0"));
            Map<String, String> tableNameMap = dmTableList.stream().collect(Collectors.toMap(dmTable -> dmTable.getSchemaName() + "." + dmTable.getTableName(), dmTable ->  dmTable.getTableNameChn()==null?"":dmTable.getTableNameChn()));
            //查询当前表的上游或者下游
            String[] tableFullNameArr = tableFullName.split("\\.");
            LineageInfo lineageInfo = lineageInfoService.getOne(new QueryWrapper<LineageInfo>()
                    .eq("schema_name", tableFullNameArr[0])
                    .eq("table_name",tableFullNameArr[1])
            );
            if(lineageInfo==null){
                return null;
            }
            List<JSONObject> childList =  new ArrayList<>();
            if(relation.equals("source")){ //上游
                String sourceTables = lineageInfo.getSourceTables();
                if(sourceTables!=null) {
                    String[] sourceTableFullNameArr = sourceTables.split(",");
                    for (String sourceTableFullName : sourceTableFullNameArr) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", sourceTableFullName);
                        jsonObject.put("relation", "source");
                        String tableNameChn = tableNameMap.get(sourceTableFullName);
                        if (tableNameChn != null) {
                            jsonObject.put("comment", tableNameChn);
                        }
                        childList.add(jsonObject);
                    }
                }
            }else{
                //下游
                String sinkTables = lineageInfo.getSinkTables();
                if(sinkTables!=null) {
                    String[] sinkTableFullNameArr = sinkTables.split(",");
                    for (String sinkTableFullName  : sinkTableFullNameArr) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", sinkTableFullName);
                        jsonObject.put("relation", "sink");
                        String tableNameChn = tableNameMap.get(sinkTableFullName);
                        if (tableNameChn != null) {
                            jsonObject.put("comment", tableNameChn);
                        }
                        childList.add(jsonObject);
                    }
                }

            }
            return Result.ok(childList) ;

        }

}
